package edu.service;

import edu.pojo.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import org.apache.log4j.Logger;

@Service
public class EmailService {
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private JavaMailSenderImpl javaMailSender;

    static Logger logger = Logger.getLogger(EmailService.class);

    /*
     * 发送普通邮件
     * */
    @Async("taskExecutor")
    public void sendMessage(String target){
        // 异步
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件发送主题
        message.setSubject("test message");
        // 设置邮件发送者,需要和application中设置的一致
        message.setFrom("csdn@fzhuangyu.top");
        // 设置邮件接收者
        message.setTo(target);
        // 设置发送日期
        message.setSentDate(new Date());
        // 设置邮件正文
        message.setText("测试邮件正文");
        // 发送邮件
        javaMailSender.send(message);
    }


    /*
     * 发送html格式邮件
     * */
    @Async("taskExecutor")
    public void sendThymeleafMail(String target, Member member) throws MessagingException {
        // 异步
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            logger.error("异常member的编号:" + member.getId());
            e.printStackTrace();
        }
        // 创建一个复杂邮件对象
        MimeMessage message = javaMailSender.createMimeMessage();
        // 创建一个复杂邮件对象的辅助对象
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);

        // 设置基本信息
        messageHelper.setSubject("CSDN message");
        messageHelper.setFrom("csdn@fzhuangyu.top");
        messageHelper.setTo(member.getEmail());

        messageHelper.setSentDate(new Date());

        // 引入thymeleaf的context
        Context context = new Context();

        // 设置其中的变量
        context.setVariable("name", member.getName());
        context.setVariable("id", member.getId());


        // 第一个参数是模板的名称
        String process = templateEngine.process(target, context);
        // 第二个参数true表示是html文本
        messageHelper.setText(process, true);

        javaMailSender.send(message);
    }
}
